/*
 * Copyright 2002-2016 the atnoce.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.atnoce.onepass.view;

import com.atnoce.onepass.Start;
import com.atnoce.onepass.core.BackService;
import com.atnoce.onepass.core.CoreUtil;
import com.atnoce.onepass.core.SecurityController;
import com.atnoce.onepass.dao.DirTypeDao;
import com.atnoce.onepass.dao.OnepassConfigDao;
import com.atnoce.onepass.dao.PasswordItemDao;
import com.atnoce.onepass.pojo.DirType;
import com.atnoce.onepass.pojo.PasswordItem;
import com.atnoce.onepass.utils.Cache;
import com.atnoce.onepass.utils.CommonUtil;
import com.atnoce.onepass.utils.QueueType;
import com.jfoenix.controls.JFXCheckBox;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXTextArea;
import com.jfoenix.controls.JFXTextField;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
import org.apache.commons.lang.StringUtils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author atnoce.com
 * @date 2016/11/6
 * @since 1.0.0
 */
public class PasswordItemEditController {

    @FXML
    private JFXTextField username;
    @FXML
    private JFXCheckBox autoGenerate;
    @FXML
    private JFXTextField pass;
    @FXML
    private Button autoGenerateBtn;
    @FXML
    private JFXComboBox<DirType> classType;
    @FXML
    private JFXTextArea beizhu;
    @FXML
    private Button saveBtn;
    @FXML
    private Button cancelBtn;
    @FXML
    private Button pwdGenSettingBtn;
    private Start start;
    private Stage dialogStage;
    private PasswordItem pdi;

    private boolean okClicked=false;

    private final DirTypeDao ctd=new DirTypeDao();
    private final PasswordItemDao pd=new PasswordItemDao();
    private final OnepassConfigDao cd=new OnepassConfigDao();

    public void setDialogStage(Stage dialogStage){
        this.dialogStage=dialogStage;
    }
    public void setStart(Start start){
        this.start=start;
    }
    public boolean isOkClicked(){
        return okClicked;
    }
    public void setPdi(PasswordItem pdi){
        this.pdi=pdi;
        if(!StringUtils.isBlank(pdi.getPassId())){
            try {
                username.setText(SecurityController.getSecurityInstence().AESdecrypt(pdi.getAccount(), Cache.getKey()));
                pass.setText(SecurityController.getSecurityInstence().AESdecrypt(pdi.getPasswordStr(), Cache.getKey()));
            } catch (Exception ex) {
            }
            beizhu.setText(pdi.getRemarkStr());
            ObservableList<DirType> items = classType.getItems();
            for(int a=0;a<items.size();a++){
                DirType get = items.get(a);
                if(StringUtils.equals(get.getDirId(), pdi.getDirTypeId())){
                    classType.getSelectionModel().select(a);
                    break;
                }
            }
            saveBtn.setOnAction(e->updatePasswordItem());
            saveBtn.setText("更新");
        }else{
            //根据用户当前选择的分类，设置选中的分类
            ObservableList<DirType> items = classType.getItems();
            for(int a=0;a<items.size();a++){
                DirType get = items.get(a);
                if(StringUtils.equals(get.getDirName(), Cache.getIndexLeftSelectedDirtype())){
                    classType.getSelectionModel().select(a);
                    break;
                }
            }
        }
    }

    @FXML
    private void initialize(){
        username.setPromptText("请在此处输入用户名");
        pass.setPromptText("手动输入密码或者自动生成密码");

        autoGenerate.setOnAction(e->{
            autoGenerateBtn.setDisable(!autoGenerate.isSelected());
            pwdGenSettingBtn.setDisable(!autoGenerate.isSelected());
        });
        pwdGenSettingBtn.setTooltip(CommonUtil.getTooltip("点击设置密码生成器",14));

        try{
            //设置分类列表的值
            classType.setItems(ctd.getDirTypes());


            //classType.getSelectionModel().select(Cache.INDEX_LEFT_SELECTED_DIRTYPE);
        }catch(SQLException e){
            CommonUtil.alert(Alert.AlertType.ERROR,null,"读取分类列表错误！"+e.getMessage(),"错误").showAndWait();
            //return;
        }catch(ClassNotFoundException e){
            CommonUtil.alert(Alert.AlertType.ERROR,null,"找不到数据库驱动!"+e.getMessage(),"错误").showAndWait();
        }

        saveBtn.setOnAction(e->saveHandler());
        // 如果修改的时候点击了取消，会报错，因为取消会返回false，窗口关闭后会执行对账号的解密，
        // 但是用户取消了修改操作，此时是不需要解密的
        cancelBtn.setOnAction(e->{
            okClicked=false;
            dialogStage.close();
        });
        autoGenerateBtn.setOnAction(e->autoGenreBtnHandler());
        pwdGenSettingBtn.setOnAction(e->pwdGenSettingHandler());



    }
    private void updatePasswordItem(){
        String selectedItem = classType.getSelectionModel().getSelectedItem().getDirName();
        if(!StringUtils.equals(selectedItem, pdi.getDirTypeId())){
            //需要删除列表中的项
        }

        if(isInputValid()){
            Cache.setAddPassItemSelectDirtype(selectedItem);

            String ume=username.getText().trim();
            String pwd=pass.getText();

            try {
                pdi.setAccount(SecurityController.getSecurityInstence().AESencrypt(ume, Cache.getKey()));
                pdi.setPasswordStr(SecurityController.getSecurityInstence().AESencrypt(pwd, Cache.getKey()));
            } catch (Exception ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,null,"修改失败!"+ex.getMessage(),"失败").showAndWait();
                okClicked=false;
                dialogStage.close();
                return;
            }
            pdi.setRemarkStr(beizhu.getText());
            //pdi.setModifyTime(CommonUtil.getTime());
            //pdi.setDirTypeId(selectedItem);
            try {
                if(pd.updatePasswordItem(pdi,selectedItem)){
                    Map<QueueType,String> map=new HashMap<>();
                    map.put(QueueType.PASSITEM,pdi.getPassId());
                    Cache.addUpdateModifyTimeQueue(map);
                    BackService.startUpdateModifyTimeService();

                    CommonUtil.alert(Alert.AlertType.INFORMATION,null,"修改成功!","成功").showAndWait();
                    okClicked=true;
                    dialogStage.close();
                }else{
                    CommonUtil.alert(Alert.AlertType.INFORMATION,null,"修改失败!","失败").showAndWait();
                    okClicked=false;
                    dialogStage.close();
                }
            } catch (Exception e1) {
                CommonUtil.alert(Alert.AlertType.INFORMATION,"保存失败","修改密码条目时发生系统错误!"+e1.getMessage(),"失败").showAndWait();
            }

        }
    }
    /**
     * 密码生成器按钮处理函数
     */
    private void autoGenreBtnHandler(){
        try {
            String generPassStr = CoreUtil.getGenerPassStr(cd.getOnepassConfig());
            pass.setText(generPassStr);
        } catch (SQLException e) {
            CommonUtil.alert(Alert.AlertType.ERROR,"生成失败","生成器发生内部错误!"+e.getMessage(),"失败").showAndWait();
        }catch(ClassNotFoundException e){
            CommonUtil.alert(Alert.AlertType.ERROR,"生成失败","找不到数据库驱动!!"+e.getMessage(),"失败").showAndWait();
        }
    }
    /**
     * 保存密码条目
     */
    private void saveHandler(){
        DirType selectedItem1 = classType.getSelectionModel().getSelectedItem();
        if (selectedItem1==null){
            CommonUtil.alert(Alert.AlertType.ERROR,"添加失败！","必须选择一个分类!","失败").showAndWait();
            return;
        }
        String selectedItem = classType.getSelectionModel().getSelectedItem().getDirName();
        if(isInputValid()){
            Cache.setAddPassItemSelectDirtype(selectedItem);

            String ume=username.getText().trim();
            String pwd=pass.getText();

            try {
                pdi.setAccount(SecurityController.getSecurityInstence().AESencrypt(ume, Cache.getKey()));
                pdi.setPasswordStr(SecurityController.getSecurityInstence().AESencrypt(pwd, Cache.getKey()));
            } catch (Exception ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,"保存失败！","添加密码条目时发生系统错误!"+ex.getMessage(),"失败").showAndWait();
                return;
            }

            pdi.setPassId(CoreUtil.getId());
            pdi.setRemarkStr(beizhu.getText());

            pdi.setCreateTime(CommonUtil.getTime());
            //pdi.setModifyTime(CommonUtil.getTime());
            pdi.setIsDelete("false");
            pdi.setSync("false");
            try {
                if(pd.addPasswordItem(pdi,selectedItem)){
                    Map<QueueType,String> map=new HashMap<>();
                    map.put(QueueType.PASSITEM,pdi.getPassId());
                    Cache.addUpdateModifyTimeQueue(map);
                    BackService.startUpdateModifyTimeService();
                    CommonUtil.alert(Alert.AlertType.INFORMATION,null,"添加成功!","成功").showAndWait();
                    okClicked=true;
                    dialogStage.close();
                }else{
                    CommonUtil.alert(Alert.AlertType.ERROR,null,"添加失败!","失败").showAndWait();
                    okClicked=false;
                    dialogStage.close();
                }
            } catch (Exception e1) {
                CommonUtil.alert(Alert.AlertType.ERROR,"保存失败","添加密码条目时发生系统错误!","失败").showAndWait();
            }

        }
    }
    private boolean isInputValid(){
        String errorMessage="";
        if(StringUtils.isBlank(username.getText().trim())){
            errorMessage+="用户名不能为空!\n";
        }else if(username.getLength()>100){
            errorMessage+="用户名长度不能超过100字符!\n";
        }
        if(StringUtils.isBlank(pass.getText())){
            errorMessage+="密码不能为空！\n";
        }else if (pass.getLength()>200){
            errorMessage+="密码长度不能超过200字符！\n";
        }
        if(classType.getSelectionModel().getSelectedItem()==null){
            errorMessage+="请选择分类！\n";
        }
        if(beizhu.getText().trim().length()>500){
            errorMessage+="备注信息不能超过500字符\n";
        }
        if(errorMessage.length()==0){
            return true;
        }else{
            CommonUtil.alert(Alert.AlertType.WARNING,null,errorMessage,"发现问题").showAndWait();
            return false;
        }

    }
    public void pwdGenSettingHandler(){
        start.showPwdGenSettingDialog();
    }
}
